package me.zhengjie.utils;

import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;


public class MapToObjectConverter {


    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public static <T> T convert(Map<String, Object> map, Class<T> clazz) throws Exception {
        T instance = clazz.newInstance();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String fieldName = entry.getKey();
            Object fieldValue = entry.getValue();
            if (fieldValue == null) {
                continue; // 跳过 null 值
            }
            try {
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                // 根据字段类型进行类型转换
                Object convertedValue = convertValue(fieldValue, field.getType());
                field.set(instance, convertedValue);
            } catch (NoSuchFieldException e) {
                // 忽略不存在的字段
            }
        }

        return instance;
    }

    private static Object convertValue(Object value, Class<?> targetType) {
        if (value == null || targetType.isAssignableFrom(value.getClass())) {
            return value;
        }
        String strValue = value.toString();
        if (targetType == LocalDateTime.class) {
            return LocalDateTime.parse(strValue, DATE_TIME_FORMATTER);
        } else if (targetType == LocalDate.class) {
            return LocalDate.parse(strValue, DATE_FORMATTER);
        } else if (targetType == Date.class) {
            try {
                // 转换为 java.util.Date
                return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(strValue);
            } catch (Exception e) {
                throw new IllegalArgumentException("Failed to parse date: " + strValue, e);
            }
        }
        // 其他基本类型转换
        if (targetType == Integer.class || targetType == int.class) {
            return Integer.valueOf(strValue);
        } else if (targetType == Long.class || targetType == long.class) {
            return Long.valueOf(strValue);
        } else if (targetType == Double.class || targetType == double.class) {
            return Double.valueOf(strValue);
        } else if (targetType == Boolean.class || targetType == boolean.class) {
            return Boolean.valueOf(strValue);
        }
        return value; // 无法转换时返回原始值
    }

}
